<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :search.sync="searchForm"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template slot-scope="scope" slot="menuLeft">
          <el-button
            type="danger"
            icon="el-icon-upload2"
            @click="() => (dialogVisible = true)"
            >批量创建班级</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-upload2"
            @click="upgradeAllClazz"
            >升级</el-button
          >
          <el-button type="primary" icon="el-icon-upload2" @click="renameAll()"
            >修复班级名称</el-button
          >
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            size="small"
            icon="el-icon-upload2"
            style="color:red"
            v-if="canUpgrade(scope.row)"
            @click="upgraeOne(scope.row, true)"
            >升级</el-button
          >
          <el-button icon="el-icon-s-check" type="text">指派班主任</el-button>
        </template>
        <template slot-scope="scope" slot="clazzGradeSearch">
          <el-radio-group v-model="searchForm.clazzGrade">
            <el-radio-button label="null">全部</el-radio-button>
            <el-radio-button label="1">一年级</el-radio-button
            ><el-radio-button label="2">二年级</el-radio-button
            ><el-radio-button label="3">三年级</el-radio-button>
          </el-radio-group>
        </template>
        <template slot-scope="scope" slot="clazzName">
          <el-tooltip
            class="item"
            effect="light"
            v-if="canRename(scope.row)"
            :content="canRename(scope.row)"
            placement="top-end"
          >
            <i
              class="el-icon-question"
              style="color:red"
              type="warning"
              @click="rename(scope.row, true)"
            ></i>
          </el-tooltip>
          {{ scope.row.clazzName }}
        </template>
        <template slot-scope="scope" slot="clazzYear">
          {{ scope.row.clazzYear }}
        </template>
      </avue-crud>
      <el-dialog> </el-dialog>
    </basic-container>
    <el-dialog title="批量创建班级" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="dialogForm" label-width="80px">
        <el-form-item label="班级数量">
          <el-input v-model="dialogForm.number" type="number" />
        </el-form-item>
        <el-form-item label="名称样式">
          <el-radio-group v-model="dialogForm.nameStyle">
            <el-radio-button label="1班"></el-radio-button>
            <el-radio-button label="高一1班"></el-radio-button>
            <el-radio-button label="高一(1)班"></el-radio-button>
            <el-radio-button label="2021级1班"></el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-alert
        title="该操作将创建本年度指定数量的高一年级的班级."
        :closable="false"
        type="error"
        effect="dark"
      >
        <span v-for="name in newClazzNames.slice(0, 10)" :key="name">
          <el-tag type="success" effect="plain" size="small">{{ name }}</el-tag>
        </span>
      </el-alert>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogClosed">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, upgrade } from "./api";
import { tableOption } from "./crud";
import { mapGetters } from "vuex";

export default {
  name: "clazz",
  data() {
    return {
      dialogVisible: false,
      dialogForm: {
        number: 30,
        nameStyle: "1班",
      },
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
    };
  },
  computed: {
    ...mapGetters([
      "permission",
      "schoolId",
      "clazzGrade",
      "clazzId",
      "yearValue",
      "homePage",
    ]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.code_clazz_add, false),
        delBtn: this.vaildData(this.permission.code_clazz_del, false),
        editBtn: this.vaildData(this.permission.code_clazz_edit, false),
      };
    },
    newClazzNames() {
      let nameArray = [];
      for (let i = 0; i < this.dialogForm.number; i++) {
        let newName = null;
        switch (this.dialogForm.nameStyle) {
          case "1班":
            newName = i + 1 + "班";
            break;
          case "高一1班":
            newName = "高一" + (i + 1) + "班";
            break;
          case "高一(1)班":
            newName = "高一(" + (i + 1) + ")班";
            break;
          case "2021级1班":
            newName = "2021级" + (i + 1) + "班";
            break;
        }
        nameArray.push(newName);
      }
      return nameArray;
    },
  },
  watch: {
    deep: true, //true 深度监听
    homePage: {
      handler(val, oldVal) {
        this.refreshChange();
      },
    },
  },
  methods: {
    dialogClosed() {
      let clazzArray = this.newClazzNames.map((name) => {
        return { clazzSchool: this.schoolId, clazzName: name };
      });
      addObj(clazzArray).then((response) => {
        this.$message.success(response.data.data);
        this.dialogVisible = false;
        this.refreshChange();
      });
    },
    renameAll() {
      for (const clazz of this.$refs.crud.tableSelect) {
        if (this.canRename(clazz)) {
          this.rename(clazz, false);
        }
      }
      this.refreshChange();
    },
    rename(clazz, reload) {
      if (!this.canRename(clazz)) {
        return;
      }
      let clazzGradeTxt = clazz.clazzGrade
        .replace("1", "一")
        .replace("2", "二")
        .replace("3", "三");
      clazz.clazzName = clazz.clazzName.replace(
        /^高(一|二|三)(.*)班$/,
        "高" + clazzGradeTxt + "$2班"
      );
      putObj({ clazzId: clazz.clazzId, clazzName: clazz.clazzName }).then(
        (response) => {
          if (reload) {
            this.refreshChange();
          } else {
            this.$message.success(response.data.data);
          }
        }
      );
    },
    canRename(clazz) {
      let clazzNameGradeTxt = clazz.clazzName.replace(
        /^高(一|二|三).*班$/gi,
        "$1"
      );
      let clazzGradeTxt = clazz.clazzGrade
        .replace("1", "一")
        .replace("2", "二")
        .replace("3", "三");
      return clazzGradeTxt == clazzNameGradeTxt
        ? undefined
        : '应为"' + clazzGradeTxt + '"年级';
    },
    upgradeAllClazz() {
      for (const clazz of this.$refs.crud.tableSelect) {
        if (this.canUpgrade(clazz)) {
          this.upgraeOne(clazz, false);
        }
      }
      this.refreshChange();
    },
    upgraeOne(clazz, reload) {
      upgrade(clazz.clazzId).then((response) => {
        if (reload) {
          this.refreshChange();
        } else {
          this.$message.success(response.data.data);
        }
      });
    },
    canUpgrade(clazz) {
      return clazz.clazzYear < this.yearValue && clazz.clazzGrade < 3;
    },
    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
            clazzYear: this.yearValue,
            clazzSchool: this.schoolId,
            clazzGrade: this.clazzGrade,
            clazzId:this.clazzId,
          },
          params,
          this.searchForm
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    rowDel: function(row, index) {
      this.$confirm("是否确认删除ID为" + row.clazzId, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function() {
          return delObj(row.clazzId);
        })
        .then((data) => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    handleUpdate: function(row, index, done, loading) {
      putObj(row)
        .then((data) => {
          this.$message.success("修改成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    handleSave: function(row, done, loading) {
      addObj(row)
        .then((data) => {
          this.$message.success("添加成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    },
  },
};
</script>
